package com.aube.plugin.user;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.aube.plugin.origin.R;
import com.aube.plugin.wap.H5WrapperActivity;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.AppShare;
import com.huyn.baseframework.model.MemberModel;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;
import com.huyn.baseframework.views.CircleImageView;
import com.ryg.dynamicload.internal.DLIntent;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by huyaonan on 16/6/30.
 */
public class WidgetUserCenter extends DLLayout implements View.OnClickListener {
    private final String TAG = "Aube/WidgetUserCenter";

    /**
     * 购物车列表
     * deviceid  videoid  from maxnum
     */
    public static final String FAVOR_LIST = "com.aube.goods.favoritesGoodsList";

    private static final int DURATION = 300;

    private ImageView mImg;
    private View mAbout, mApp, mSetting, mCollection;
    private TextView mName;

    private View mSettingLayout, mShareLayout;
    private LinearLayout mUserLayout, mPushLayout;

    private TextView mSettingTitle, mCacheSize;
    private View mPraise, mFeedback, mClearCache, mExit;
    private View mShareWechat, mShareTimeline, mShareWeibo;

    private View mIcon;
    private ImageView mShareBack, mBack, mSettingBack, mShareImg, mShareWechatImg, mShareTimelineImg, mShareWeiboImg, mPraiseImg;

    private View mCollectionsLayout;

    private static final int MAX_NUM  =10;

    private String mLastId="";
    private int from = 0;

    private TextView mTitle;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private CollectionAdapter mAdapter;

    private List<GoodsItem> goodsItems;
    private boolean mDataLoadFinished=false, mDataLoading=false;

    private SwitchButton mSwitchButton;

    public WidgetUserCenter(Context context) {
        this(context, null);
    }

    public WidgetUserCenter(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WidgetUserCenter(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void initViews() {
        inflate(R.layout.layout_usercenter, this, true);

        mUserLayout = (LinearLayout) findViewById(R.id.user_layout);
        mSettingLayout = findViewById(R.id.user_setting_layout);
        mShareLayout = findViewById(R.id.user_share_layout);
        mShareBack = (ImageView) findViewById(R.id.share_back);
        mCollectionsLayout = findViewById(R.id.user_collecion_layout);

        int size = getResources().getDimensionPixelSize(R.dimen.head_size);
        mImg = new CircleImageView(context);
        LinearLayout.LayoutParams prams = new LinearLayout.LayoutParams(size, size);
        mUserLayout.addView(mImg, 0, prams);

        mName = (TextView) findViewById(R.id.user_name);
        mCollection = findViewById(R.id.user_collecion);
        mAbout = findViewById(R.id.user_about);
        mApp = findViewById(R.id.user_recommend);
        mFeedback = findViewById(R.id.user_feedback);
        mSetting = findViewById(R.id.user_setting);

        mSettingBack = (ImageView) findViewById(R.id.setting_topbar_back);
        mSettingTitle = (TextView) findViewById(R.id.setting_topbar_title);
        mCacheSize = (TextView) findViewById(R.id.cache_size);

        mPraise = findViewById(R.id.to_praiseus);
        mPraiseImg = (ImageView) findViewById(R.id.to_praiseus_img);
        mClearCache = findViewById(R.id.to_managecache);
        mExit = findViewById(R.id.to_exit);

        mShareWechat = findViewById(R.id.share_wechat);
        mShareTimeline = findViewById(R.id.share_timeline);
        mShareWeibo = findViewById(R.id.share_weibo);

        mShareImg = (ImageView) findViewById(R.id.share_img);
        mShareWechatImg = (ImageView) findViewById(R.id.share_wechat_img);
        mShareWeiboImg = (ImageView) findViewById(R.id.share_weibo_img);
        mShareTimelineImg = (ImageView) findViewById(R.id.share_timeline_img);

        mPushLayout = (LinearLayout) findViewById(R.id.to_managepush);
        mSwitchButton = new SwitchButton(context);
        mPushLayout.addView(mSwitchButton);
        mSwitchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                togglePush();
            }
        });

        mTitle = (TextView) findViewById(R.id.collection_topbar_title);
        mBack = (ImageView) findViewById(R.id.collection_topbar_back);
        mRecyclerView = (RecyclerView) findViewById(R.id.collections_list);

        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(context);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mTitle.setText("购物车");

        mShareBack.setOnClickListener(this);
        mImg.setOnClickListener(this);
        mName.setOnClickListener(this);
        mCollection.setOnClickListener(this);
        mAbout.setOnClickListener(this);
        mApp.setOnClickListener(this);
        mSetting.setOnClickListener(this);

        mSettingBack.setOnClickListener(this);
        mPraise.setOnClickListener(this);
        mFeedback.setOnClickListener(this);
        mClearCache.setOnClickListener(this);
        mExit.setOnClickListener(this);

        mShareWechat.setOnClickListener(this);
        mShareTimeline.setOnClickListener(this);
        mShareWeibo.setOnClickListener(this);

        mSettingTitle.setText("设置");
        mSettingTitle.setTextColor(Color.WHITE);

        Drawable backDrawable = getResources().getDrawable(R.drawable.icon_new_back);
        mShareBack.setImageDrawable(backDrawable);
        mBack.setImageDrawable(backDrawable);
        mSettingBack.setImageDrawable(backDrawable);

        mShareWechatImg.setImageDrawable(getResources().getDrawable(R.drawable.icon_wechat));
        mShareWeiboImg.setImageDrawable(getResources().getDrawable(R.drawable.icon_weibo));
        mShareTimelineImg.setImageDrawable(getResources().getDrawable(R.drawable.icon_pyq));
        mPraiseImg.setImageDrawable(getResources().getDrawable(R.drawable.icon_rightarrow));

        int statusHeight = SysUtil.getStatusHeight(getContext());
        if(statusHeight > 0) {
            mSettingLayout.setPadding(0, statusHeight, 0, 0);
            mShareBack.setPadding(0, statusHeight, 0, 0);
            mCollectionsLayout.setPadding(0, statusHeight, 0, 0);
        }

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitCollections();
            }
        });

        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (mDataLoadFinished || mAdapter == null)
                    return;
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (mLayoutManager.findLastVisibleItemPosition() == mAdapter.getItemCount() - 1) {
                        onLoadMore();
                    }
                }
            }
        });

        GradientDrawable gd = new GradientDrawable();
        gd.setCornerRadius(10);
        gd.setColor(0xffff3300);
        mExit.setBackgroundDrawable(gd);

        update();
    }

    @Override
    public void fillData(Object o) {
    }

    @Override
    public void notifyAnim(int i) {

    }

    @Override
    public void registToManager(IPositionManager iPositionManager) {

    }

    @Override
    public void unreistFromManager(IPositionManager iPositionManager) {

    }

    @Override
    public int[] getLocations() {
        return new int[0];
    }

    public void setTheme(int themeColor) {
        if(mSwitchButton != null) {
            mSwitchButton.setTintColor(themeColor);
            mSwitchButton.setCheckedNoEvent(isPushOn());
        }
    }

    public Drawable getDefaultDrawable() {
        return new BitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.bk_default));
    }

    @Override
    public void attachViews(View... view) {
        if(view != null && view.length >= 1)
            mIcon = view[0];
    }

    public void update() {
        if(UserUtil.isUserLogin()) {
            MemberModel memberModel = UserUtil.getMember();
            if(memberModel == null)
                return;
            ImageLoader.getInstance(context).fillImage(mImg, memberModel.headPic, 400, 400);
            mName.setText(memberModel.nickname);
            mExit.setVisibility(View.VISIBLE);
        } else {
            mImg.setImageDrawable(getResources().getDrawable(R.drawable.loginmr));
            mName.setText("点击登录");
            mExit.setVisibility(View.GONE);
        }
        if(mSwitchButton != null)
            mSwitchButton.setCheckedNoEvent(isPushOn());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        clickView(id);
    }

    private void clickView(int id) {
        if(id == mAbout.getId()) {
            if(mBridge != null)
                mBridge.onClickToWap(null, UserUtil.getAboutMeUrl(), false);
        } else if(id == mApp.getId()) {
            toShare();
        } else if(id == mSetting.getId()) {
            toSetting();
        } else if(id == mFeedback.getId()) {
            sendFeedback();
        } else if(id == mSettingBack.getId()) {
            exitSetting();
        } else if(id == mPraise.getId()) {
            toPraiseUs();
        } else if(id == mClearCache.getId()) {
            clearCache();
        } else if(id == mExit.getId()) {
            logout();
        } else if(id == mShareWechat.getId()) {
            toShare(false);
        } else if(id == mShareTimeline.getId()) {
            toShare(true);
        } else if(id == mShareWeibo.getId()) {
            toShareWeibo();
        } else if(id == mImg.getId() || id == mName.getId()) {
            if(mBridge != null)
                mBridge.isUserLogin();
        } else if(id == mShareBack.getId()) {
            exitShare();
        } else if(id == mCollection.getId()) {
//            if(mBridge != null) {
//                if(mBridge.isUserLogin())
                    showCollections();
//            }
        }
    }

    public boolean isPushOn() {
        if(mBridge != null) {
            return mBridge.isPushOn();
        }
        return false;
    }

    public void togglePush() {
        if(mBridge != null)
            mBridge.tooglePush();
    }

    public void toPraiseUs() {
        try {
            Uri uri = Uri.parse("market://details?id=" + getContext().getPackageName());
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            getContext().startActivity(it);
        } catch (Exception e) {
            Utils.showToast(getContext(), "手机没有安装应用市场，暂时无法评分");
        }
    }

    public void sendFeedback() {
        if(mBridge != null) {
//            mBridge.onClickToWap(null, UserUtil.getFeedBackUrl(), true);
            DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.wap.H5WrapperActivity");
            intent.putExtra(H5WrapperActivity.WEB_POST, true);
            intent.putExtra(H5WrapperActivity.WEB_URL, UserUtil.getFeedBackUrl());
            mBridge.openPluginActivity(intent);
        }
    }

    public void clearCache() {
        try {
            File cacheDir = new File(getContext().getCacheDir(), Volley.DEFAULT_CACHE_DIR);
            deleteFile(cacheDir);
            Utils.showToast(getContext(), "缓存清理完成");
            getCacheSize();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getCacheSize() {
        try {
            File cacheDir = new File(getContext().getCacheDir(), Volley.DEFAULT_CACHE_DIR);
            long size = getFileSize(cacheDir);
            mCacheSize.setText(Formatter.formatFileSize(getContext(), size));
            mCacheSize.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
            mCacheSize.setVisibility(View.GONE);
        }
    }

    private long getFileSize(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    private void deleteFile(File f) throws Exception {
        if(f.isFile()) {
            f.delete();
            return;
        }
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                deleteFile(flist[i]);
            } else {
                flist[i].delete();
            }
        }
    }

    private void showCollections() {
        ObjectAnimator animExit = ObjectAnimator.ofFloat(mUserLayout, "translationX", 0, -mUserLayout.getWidth());
        animExit.setDuration(DURATION);

        ObjectAnimator iconExit = ObjectAnimator.ofFloat(mIcon, "translationX", 0, -mUserLayout.getWidth());
        iconExit.setDuration(DURATION);

        ObjectAnimator animIn = ObjectAnimator.ofFloat(mCollectionsLayout, "translationX", mUserLayout.getWidth(), 0);
        animIn.setDuration(DURATION);
        animIn.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mCollectionsLayout.setVisibility(View.VISIBLE);
                getData();
            }
        });

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animExit, animIn, iconExit);
        set.start();
    }

    private void exitCollections() {
        ObjectAnimator animExit = ObjectAnimator.ofFloat(mCollectionsLayout, "translationX", 0, mUserLayout.getWidth());
        animExit.setDuration(DURATION);
        animExit.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mCollectionsLayout.setVisibility(View.GONE);
            }
        });

        ObjectAnimator animIn = ObjectAnimator.ofFloat(mUserLayout, "translationX", -mUserLayout.getWidth(), 0);
        animIn.setDuration(DURATION);

        ObjectAnimator iconIn = ObjectAnimator.ofFloat(mIcon, "translationX", -mUserLayout.getWidth(), 0);
        iconIn.setDuration(DURATION);

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animExit, animIn, iconIn);
        set.start();
    }

    public void exitSetting() {
        ObjectAnimator animExit = ObjectAnimator.ofFloat(mSettingLayout, "translationX", 0, mUserLayout.getWidth());
        animExit.setDuration(DURATION);
        animExit.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mSettingLayout.setVisibility(View.GONE);
            }
        });

        ObjectAnimator animIn = ObjectAnimator.ofFloat(mUserLayout, "translationX", -mUserLayout.getWidth(), 0);
        animIn.setDuration(DURATION);

        ObjectAnimator iconIn = ObjectAnimator.ofFloat(mIcon, "translationX", -mUserLayout.getWidth(), 0);
        iconIn.setDuration(DURATION);

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animExit, animIn, iconIn);
        set.start();
    }

    public void toSetting() {
        getCacheSize();
        ObjectAnimator animExit = ObjectAnimator.ofFloat(mUserLayout, "translationX", 0, -mUserLayout.getWidth());
        animExit.setDuration(DURATION);

        ObjectAnimator iconExit = ObjectAnimator.ofFloat(mIcon, "translationX", 0, -mUserLayout.getWidth());
        iconExit.setDuration(DURATION);

        ObjectAnimator animIn = ObjectAnimator.ofFloat(mSettingLayout, "translationX", mUserLayout.getWidth(), 0);
        animIn.setDuration(DURATION);
        animIn.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mSettingLayout.setVisibility(View.VISIBLE);
            }
        });

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animExit, animIn, iconExit);
        set.start();
    }

    public void exitShare() {
        ObjectAnimator animExit = ObjectAnimator.ofFloat(mShareLayout, "translationX", 0, mUserLayout.getWidth());
        animExit.setDuration(DURATION);
        animExit.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mShareLayout.setVisibility(View.GONE);
            }
        });

        ObjectAnimator animIn = ObjectAnimator.ofFloat(mUserLayout, "translationX", -mUserLayout.getWidth(), 0);
        animIn.setDuration(DURATION);

        ObjectAnimator iconIn = ObjectAnimator.ofFloat(mIcon, "translationX", -mUserLayout.getWidth(), 0);
        iconIn.setDuration(DURATION);

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animExit, animIn, iconIn);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mShareImg.setImageDrawable(null);
            }
        });
        set.start();
    }

    public void toShare() {
        mShareImg.setImageDrawable(getResources().getDrawable(R.drawable.img_taste));
        ObjectAnimator animExit = ObjectAnimator.ofFloat(mUserLayout, "translationX", 0, -mUserLayout.getWidth());
        animExit.setDuration(DURATION);

        ObjectAnimator iconExit = ObjectAnimator.ofFloat(mIcon, "translationX", 0, -mUserLayout.getWidth());
        iconExit.setDuration(DURATION);

        ObjectAnimator animIn = ObjectAnimator.ofFloat(mShareLayout, "translationX", mUserLayout.getWidth(), 0);
        animIn.setDuration(DURATION);
        animIn.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mShareLayout.setVisibility(View.VISIBLE);
            }
        });

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animExit, animIn, iconExit);
        set.start();
    }

    public void logout() {
        //clear user info
        UserUtil.logout(getContext());

        exitSetting();

        update();
    }

    public void toShare(final boolean isTimeline) {
        final AppShare appShare = UserUtil.getAppShare();
        if(appShare == null)
            return;
        ImageLoader.getInstance(context).preloadBitmap(appShare.picurl, new ImageLoader.IPreloadCallback<Bitmap>() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                ShareModule shareModule = new ShareModule(appShare.title, appShare.content, appShare.url);
                shareModule.imgBm = bitmap;
                shareModule.mShareChannel = isTimeline ? ShareType.TIMELINE : ShareType.WECHAT;
                if(mBridge != null)
                    mBridge.doShare(shareModule);
            }

            @Override
            public void onFail() {

            }
        });
    }

    public void toShareWeibo() {
        final AppShare appShare = UserUtil.getAppShare();
        if(appShare == null)
            return;
        ImageLoader.getInstance(context).preloadBitmap(appShare.picurl, new ImageLoader.IPreloadCallback<Bitmap>() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                ShareModule shareModule = new ShareModule(appShare.title, appShare.content, appShare.url);
                shareModule.imgBm = bitmap;
                shareModule.mShareChannel = ShareType.WEIBO;
                if(mBridge != null)
                    mBridge.doShare(shareModule);
            }

            @Override
            public void onFail() {

            }
        });
    }

    public boolean onBackPressed() {
        if(mSettingLayout.getVisibility() == View.VISIBLE) {
            exitSetting();
            return true;
        } else if(mShareLayout.getVisibility() == View.VISIBLE) {
            exitShare();
            return true;
        } else if(mCollectionsLayout.getVisibility() == View.VISIBLE) {
            exitCollections();
            return true;
        } else {
            return false;
        }
    }

    private void onLoadMore() {
        if(mDataLoading)
            return;
        mDataLoading = true;
        getData();
    }

    private class CollectionAdapter extends RecyclerView.Adapter<CollectionHolder> {

        @Override
        public CollectionHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = inflate(R.layout.item_collection, viewGroup, false);
            CollectionHolder holder = new CollectionHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(CollectionHolder viewHolder, int i) {
            viewHolder.init(getItem(i));
        }

        private GoodsItem getItem(int pos) {
            return goodsItems.get(pos);
        }

        @Override
        public int getItemCount() {
            return (goodsItems == null ? 0 : goodsItems.size());
        }
    }

    private class CollectionHolder extends RecyclerView.ViewHolder {

        private ImageView mLogo;
        private TextView mTitle, mDes, mOperator;

        public CollectionHolder(View itemView) {
            super(itemView);

            mLogo = (ImageView) itemView.findViewById(R.id.goods_logo);
            mDes = (TextView) itemView.findViewById(R.id.goods_title);
            mOperator = (TextView) itemView.findViewById(R.id.goods_operator);
            mTitle = (TextView) itemView.findViewById(R.id.goods_des);
        }

        public void init(final GoodsItem item) {
            ImageLoader.getInstance(context).fillImage(mLogo, getDefaultDrawable(), item.picurl, 200, 200);
            mTitle.setText(item.tlTitle);

//            SpannableString ss = new SpannableString(item.price);
//            ss.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            mDes.setText(item.tlDesc);

            mOperator.setText(item.goodstypedesc);
            mOperator.setBackgroundDrawable(getResources().getDrawable(R.drawable.bk_card_operator));
            mOperator.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mBridge != null)
                        mBridge.onClickToWap(null, item.goodsURL, true);
                }
            });
        }

    }

    public void getData() {
        HashMap<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put(Constant.API_REQUEST_METHOD, FAVOR_LIST);
//        parameterMap.put("from", from+"");
//        if (StringUtils.isNotBlank(mLastId))
//            parameterMap.put("lastId", mLastId);
        parameterMap.put("maxnum", MAX_NUM + "");
        if (mBridge != null)
            mBridge.exeHttpRequest(parameterMap, GoodsFavorListModel.class, null, new Response.Listener<GoodsFavorListModel>() {

                @Override
                public void onResponse(GoodsFavorListModel response) {
                    if (response.success()) {
                        setupData(response);
                    } else {
                        Utils.showToast(getContext(), response.errormsg);
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                }

                @Override
                public void onStart() {
                }
            });
    }

    public void setupData(GoodsFavorListModel model) {
        Utils.Log(TAG, "[setupData] In");

        if(model.data == null) {
            mDataLoadFinished = true;
            return;
        }

        List<GoodsItem> contents = model.getGoodsList();
        from = contents.size();

        mTitle.setText("购物车 (" + from + ")");

        mLastId = model.getLastId();
        if(contents.size() < MAX_NUM)
            mDataLoadFinished = true;

        if(mAdapter == null) {
            if(contents != null)
                goodsItems = contents;
            mAdapter = new CollectionAdapter();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            if(goodsItems == null)
                goodsItems = new ArrayList<>();

            goodsItems.clear();

            if(contents != null) {
                goodsItems.addAll(contents);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

}
